import { ParameterDto } from '../dtos';
import { entityToDto, dtoToEntity } from '../assembler/parameterAssembler';
import { getCustomRepository } from 'typeorm';
import { ParameterRepository } from '../repositories/parameterRepository';

export interface IParameterService {
  save(dto: ParameterDto): Promise<number>
  saveOrUpdateByProductAndName(dto: ParameterDto): Promise<number>;
  findByProduct(productName: string): Promise<ParameterDto[]>;
  findByProductAndName(productName: string, parameterName: string): Promise<ParameterDto | undefined>;
}

export class ParameterService implements IParameterService {

  private parameterRepository: ParameterRepository;

  constructor() {
    this.parameterRepository = getCustomRepository(ParameterRepository);
  }

  async save(dto: ParameterDto): Promise<number> {
    const entity = this.parameterRepository.create(dtoToEntity(dto));
    await this.parameterRepository.save(entity);
    return entity.id;
  }

  async findByProduct(productName: string): Promise<ParameterDto[]> {
    const parameterEntities = await this.parameterRepository.findByProduct(productName);
    return parameterEntities.map(e => entityToDto(e));
  }

  async findByProductAndName(productName: string, parameterName: string): Promise<ParameterDto | undefined> {
    const parameterEntity = await this.parameterRepository.findByProductAndName(productName, parameterName);
    return entityToDto(parameterEntity);
  }

  async saveOrUpdateByProductAndName(dto: ParameterDto): Promise<number> {
    const parameterEntity = await this.findByProductAndName(dto.productName, dto.name);
    return await this.save(parameterEntity ? { ... parameterEntity, ... dto } : dto);
  }
}